package com.qubi.exchange.security.auth.client.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qubi.exchange.security.auth.client.annotation.IgnoreUserToken;
import com.qubi.exchange.security.auth.client.config.UserAuthConfig;
import com.coin.common.dto.auth.UserInfoDto;
import com.qubi.exchange.security.auth.client.jwt.UserAuthUtil;

import com.qubi.exchange.security.common.context.BaseContextHandler;
import com.qubi.exchange.security.common.exception.auth.UserTokenException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wx on 2017/9/10.
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(UserAuthRestInterceptor.class);

    @Autowired
    private UserAuthUtil userAuthUtil;



    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;
    private String getCsrfTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(userAuthConfig.getTokenHeader());
        if (org.springframework.util.StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }
        return null;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 配置该注解，说明不进行用户拦截
        IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        }
        if (annotation != null) {
            return super.preHandle(request, response, handler);
        }
        String token = getCsrfTokenFromRequest(request);

        if(StringUtils.isEmpty(token))       throw new UserTokenException("User token expired!");
        String key = "USER_TOKEN:" + token;
        Object object = redisTemplate.opsForValue().get(key);

        if (object == null ) {
            logger.warn("queryUserInfoByToken from cache is empty. key:{}", key);
            throw new UserTokenException("用户票据已经过期");
        }
        UserInfoDto userInfoDto = null;
        try {
            String userInfoDtoStr=object.toString();

            userInfoDto = JSONObject.parseObject(userInfoDtoStr,UserInfoDto.class);
        } catch (java.lang.ClassCastException er) {
            logger.warn("queryUserInfoByToken has ClassCastException. key:{}, object:{}, er", key, object, er);
            throw new UserTokenException("用户票据已经过期");
        }

            BaseContextHandler.setUserID(userInfoDto.getUid().toString());

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

    public static String getUserId(String token) {
        String[] s = token.split(";");
        Map<String, String> params = new HashMap<>(8);
        for (String t : s) {
            if (!StringUtils.isEmpty(t)) {
                String[] p = t.split("\\|");
                String []k=t.split(":");
                params.put(p[0], k[k.length-1]);
            }
        }
        return params.get("investorid").replace("\"","").replace("\\","");
    }

    public static void main(String[] args) {
      var id=  getUserId("investorid|s:10:\"i000083571\";accountstate|i:2;");
        System.out.println(id);
    }




}
